<template>
  <div style="background-color:white ;padding: 5px">
    <el-row>
      <div>
        <div style="display: inline-block">
          <el-button icon="el-icon-back" size="small" style="font-family: Microsoft YaHei" type="text"
                     @click="returnPage">返回
          </el-button>
        </div>
        <div style="display: inline-block">|</div>
        <div style="display: inline-block;">
          <div style="padding-bottom: 15px;">
            <span style="font-family: Microsoft YaHei;display: inline-block; font-size: 14px;">知识导出申请结果</span>
          </div>
        </div>
        <div style="border-bottom: solid 1px #C9C9C9;"></div>
      </div>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div>
          <div style="width: 430px; float: right; padding: 10px;">
            <el-input v-model="name"
                      placeholder="请输入知识包名称"
                      @keyup.enter.native="searchEnterFun($event)">
              <i class="el-input__icon el-icon-search"
                 slot="prefix"></i>
              <el-button :icon="appendIcon"
                         slot="append"
                         v-on:click="switchAppend"></el-button>
            </el-input>
          </div>
          <div id="advance"
               style="padding: 10px; float: right;"
               v-if="showAdvance">
            <div>
              <div style="margin-top: 10px; display: flex;">
                <div class="advancedSearchLabel">所属知识库</div>
                <div style="width: 240px">
                  <el-cascader :options="knowledgeLibOptions"
                               :props="cascadeProps"
                               :show-all-levels="false"
                               clearable
                               placeholder="所属知识库"
                               @change="handleChange"
                               v-model="knowledgeLibId"></el-cascader>
                </div>
              </div>
            </div>
            <div>
              <div style="margin-top: 10px; display: flex;">
                <div class="advancedSearchLabel">创建日期</div>
                <div>
                  <el-date-picker
                    v-model="createdTime"
                    @change="dateChange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format=" yyyy-MM-dd" format="yyyy-MM-dd"
                    style="width: 240px;">
                  </el-date-picker>
                </div>
              </div>
            </div>
            <div>
              <div style="margin-top: 10px; display: flex;">
                <div class="advancedSearchLabel">导出类型</div>
                <div style="width: 240px; height: 40px;">
                  <el-select class="item-choose" style="width: 100%;" v-model="exportType" size="small">
                    <el-option value="1" label="EXCEL格式">EXCEL格式</el-option>
                    <el-option value="2" label="XML格式">XML格式</el-option>
                  </el-select>
                </div>
              </div>
            </div>
            <div style="margin-top: 30px; right: 10px;">
              <el-row>
                <el-col :offset="6" :span="6">
                  <div style="margin-left: 90px;height: 32px; width: 88px;">
                    <el-button size="small" v-on:click="advanceCancel">取 消</el-button>
                  </div>
                </el-col>
                <el-col :offset="2" :span="2">
                  <div style="margin-left: 30px;height: 32px; width: 88px;">
                    <el-button size="small" v-on:click="reset">重置</el-button>
                  </div>
                </el-col>
                <el-col :offset="2" :span="2">
                  <div div style="margin-left: 30px;height: 32px; width: 88px;">
                    <el-button size="small" type="success" v-on:click="advanceConfirm" >确 定</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-table highlight-current-row :data="tableData" :height="tableHeight" border style="width: 100%">
          <el-table-column prop="name" label="导出知识包名称" min-width="180"></el-table-column>
          <el-table-column prop="knowledgeLibName" label="所属知识库" min-width="180"></el-table-column>
          <el-table-column prop="downloadTotal" label="下载次数" min-width="80"></el-table-column>
          <el-table-column prop="createdTime" label="创建时间" min-width="180" :formatter="dateFormat"></el-table-column>
          <el-table-column prop="cause" label="导出原因" min-width="240"></el-table-column>
          <el-table-column label="导出类型" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.type===1">EXCEL格式</span>
              <span v-if="scope.row.type===2">XML格式</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="150">
            <template slot-scope="scope">
              <span><el-link type="primary" @click.prevent="download(scope.row)">下载</el-link></span>
              <span><el-link type="danger" @click.prevent="del(scope.row.id)">删除</el-link></span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-pagination :total="totalNum" :page-size="pageSize"  @current-change="handleCurrentChange" background
                     layout="total, prev, pager, next, jumper" v-if="multiplePages" style="text-align: right;margin-top: 10px;"></el-pagination>
    </el-row>
  </div>
</template>

<script>
import moment from "moment";

export default {
  name: "ExportApplyResultList",
  data() {
    return {
      name:'',
      knowledgeLibId:'',
      knowledgeLibOptions: [],
      exportType:"",
      createdTime:"",
      cascadeProps: { multiple: false },
      multiplePages: true,
      appendIcon: "el-icon-caret-bottom",
      showAdvance: false,
      noData: true,
      totalNum: 0,
      tableData: [],
      currentPage: 0, // 第几页
      pageSize: 10, // 每页显示的数据个数
      tableHeight: 0 // 表格高度
    }
  },
  methods : {
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getTableData();
    },
    dateFormat: function (row, column) {
      const date = row[column.property]
      if (date == undefined) {
        return ''
      }
      return moment(date).format("YYYY-MM-DD  HH:mm:ss")
    },
    getTableData: function () {
      this.axios.get('/pmph/action/knowledgeLib/selectExportApplyList', {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          name: this.name,
          createdTime: this.createdTime.toString(),
          exportType: this.exportType.toString(),
          knowledgeLibId: this.knowledgeLibId.toString()
        }
      }).then((response) => {
        this.noData = response.data.total <= 0;
        this.tableData = response.data.records;
        this.totalNum = response.data.total;
      }).catch((error) => {
        console.error(error);
        this.tableData = [];
        this.noData = true;
        this.$message.error("未能请求到数据");
      })
    },
    del: function (val) {
      this.$confirm('确定删除本条知识导出申请？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO 后台删除数据
        this.axios.get('/pmph/action/knowledgeLib/deleteExportApplyById', {
          params: {
            id: val
          }
        }).then((response) => {
          const self = this;
          this.getTableData()
        }).catch((error) => {
          console.log("错误***" + error);
          this.$message.error("删除失败");
        });
      })
    },
    download: function(row) {
      console.log("知识库ID" + row.knowledgeLibId);
      // excel
      const self = this;
      if (1 === row.type) {
        this.axios.get('/pmph/action/knowledgeLib/downloadExportApply', {
          params: {
            id: row.id,
            downloadTotal: row.downloadTotal,
            exclude: row.exclude,
            type: row.type,
            name: row.name,
            knowledgeLibName: row.knowledgeLibName,
            knowledgeLibId: row.knowledgeLibId
          },
          headers: {
            'Content-Type': 'application/json; application/octet-stream'
          },
          responseType: 'blob'
        }).then((response) => {
          console.log(response);
          this.downloadFile(response.data, row.name, row.type);
          this.getTableData()
        });
      } else {
        this.$prompt('请输入密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.axios.get('/pmph/action/knowledgeLib/downloadExportApply', {
            params: {
              password: value,
              id: row.id,
              downloadTotal: row.downloadTotal,
              includeDynamicField: row.includeDynamicField,
              exclude: row.exclude,
              type: row.type,
              name: row.name,
              knowledgeLibName: row.knowledgeLibName,
              knowledgeLibId: row.knowledgeLibId
            },
            responseType: 'blob',
            headers: {
              'Content-Type': 'application/zip; application/octet-stream'
            }
          }).then((response) => {
            this.downloadFile(response.data, row.name, row.type);
            this.getTableData();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      }
    },
    downloadFile(data, knowledgeLibName, type) {
      // 文件导出
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data],{type: "application/octet-stream"}));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      if (1 === type) {
        link.setAttribute('download', knowledgeLibName + '.xlsx');
      } else {
        link.setAttribute('download', knowledgeLibName + '.zip');
      }
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放blob对
    },
    searchEnterFun (e) {
      const keyCode = window.event ? e.keyCode : e.which;
      console.log("回车搜索", keyCode, e);
      if (keyCode === 13) {
        this.currentPage = 0;
        this.getTableData();
      }
    },
    handleChange (value) {
      this.knowledgeLibId = value;
    },
    exportTypeHandleChange (value) {
      this.exportType = value;
    },
    dateChange(val) {
      this.createdTime = val;
    },
    switchAppend: function () {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
      this.showKnowledgeLibItems();
    },
    showKnowledgeLibItems: function () {
      // 获取分类数据
      this.axios.get("/pmph/action/knowledgeLib/selectAllKnowledgeLib").then((response) => {
        this.knowledgeLibOptions = response.data;
      }).catch((error) => {
        this.$message.error("获取知识库数据失败");
      })
    },
    advanceCancel: function () {
      this.showAdvance = false;
    },
    reset: function () {
      this.name = '';
      this.knowledgeLibId = '';
      this.createdTime = '';
      this.exportType = '';
    },
    advanceConfirm: function () {
      this.currentPage = 0;
      this.showAdvance = false;
      this.getTableData();
    },
    returnPage() {
      if (window.history.length <= 1) {
        this.$router.push({path: "/zh-CN/home"});
        return false;
      } else {
        this.$router.go(-1);
      }
    }
  },
  mounted: function () { //页面初始化方法
    const mountedThat = this;
    mountedThat.getTableData(mountedThat);
  },
  created() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 180
  }
}
</script>
